package com.android.fastride.model.repository;


import com.android.fastride.FastRideApplication;
import com.android.fastride.exception.DownloadException;
import com.android.fastride.exception.NetworkNotConnectException;
import com.android.fastride.model.http.entity.RxBean;
import com.android.fastride.model.http.entity.UpdateEntity;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import rx.Observable;
import rx.Subscriber;

/**
 * 更新apk操作仓库
 * Created by pengyuantao on 2017/9/21 13:46.
 */

public class UpdateApkRepository {

  //保存的文件名称
  public static final String UPDATE_APK = "update.apk";

  /**
   * 获取更新信息
   *
   * @return 返回下载更新信息
   */
  public static Observable<UpdateEntity> getUpdateInfo() {
    return FastRideApplication.getApp().getControlSysService().getUpdateInfo();
  }

  /**
   * 开始下载apk
   *
   * @param url 更新apk路径
   * @return 返回apk本地的安装路径
   */
  public static Observable<RxBean> downloadApk(String url) {
    return Observable.<RxBean>unsafeCreate(new Observable.OnSubscribe<RxBean>() {
      @Override
      public void call(Subscriber<? super RxBean> subscriber) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        builder.connectTimeout(5, TimeUnit.SECONDS);
        OkHttpClient downloadClient = builder.build();
        try {
          Request.Builder builder1 = new Request.Builder();
          Request request = builder1.url(url).get().build();
          okhttp3.Response response = downloadClient.newCall(request).execute();

          if (response != null && response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            //开始进行IO操作
            File updateFile = new File(FastRideApplication.getApp().getCacheDir(), UPDATE_APK);
            BufferedOutputStream bos = null;
            BufferedInputStream bis = null;
            double downloadCount = 0f;
            double fileSize = responseBody.contentLength();

            bos = new BufferedOutputStream(new FileOutputStream(updateFile));
            bis = new BufferedInputStream(responseBody.byteStream());
            //开始进行读写操作
            byte[] cache = new byte[2048];
            int len = 0;
            while ((len = bis.read(cache)) != -1) {
              bos.write(cache, 0, len);
              downloadCount += len;
              float percent = (float) (downloadCount / fileSize)*100;
              subscriber.onNext(RxBean.obtain().setValue((int) percent, null));
            }
            bos.flush();
            subscriber.onNext(RxBean.obtain().setValue(100, updateFile.getAbsolutePath()));
            subscriber.onCompleted();
          } else {
            if (response == null) {
              subscriber.onError(new NetworkNotConnectException("download fail"));
            } else {
              subscriber.onError(new DownloadException(
                  "code:" + response.code() + "  message:" + response.message()));
            }
          }
        } catch (IOException e) {
          e.printStackTrace();
          subscriber.onError(e);
        }
      }
    }).sample(500, TimeUnit.MILLISECONDS);
  }

}
